package com.lsq.oss;

import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.core.sync.ResponseTransformer;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.*;

import java.io.File;
import java.io.IOException;
import java.util.List;

public class S3Example {
    // 初始化S3客户端（推荐单例模式）
    private static S3Client getS3Client() {
        // 配置区域（根据实际情况修改，如us-east-1、ap-southeast-1等）
        Region region = Region.US_EAST_1;
        return S3Client.builder()
                .region(region)
                // 凭证会自动从环境变量或~/.aws/credentials读取
                .build();
    }

    // 1. 创建存储桶（Bucket名称必须全局唯一）
    public static void createBucket(String bucketName) {
        S3Client s3 = getS3Client();
        try {
            CreateBucketRequest request = CreateBucketRequest.builder()
                    .bucket(bucketName)
                    .build();
            s3.createBucket(request);
            System.out.println("桶 " + bucketName + " 创建成功");
        } catch (S3Exception e) {
            System.err.println("创建桶失败：" + e.awsErrorDetails().errorMessage());
        } finally {
            s3.close(); // 关闭客户端释放资源
        }
    }

    // 2. 上传文件到S3（对象）
    public static void uploadObject(String bucketName, String objectKey, String localFilePath) {
        S3Client s3 = getS3Client();
        try {
            File file = new File(localFilePath);
            PutObjectRequest request = PutObjectRequest.builder()
                    .bucket(bucketName)
                    .key(objectKey) // S3中对象的唯一标识（类似文件路径）
                    .build();
            // 上传文件内容
            s3.putObject(request, RequestBody.fromFile(file));
            System.out.println("文件 " + localFilePath + " 上传成功，对象Key：" + objectKey);
        } catch (S3Exception e) {
            System.err.println("上传失败：" + e.getMessage());
        } finally {
            s3.close();
        }
    }

    // 3. 从S3下载对象到本地文件
    public static void downloadObject(String bucketName, String objectKey, String localFilePath) {
        S3Client s3 = getS3Client();
        try {
            GetObjectRequest request = GetObjectRequest.builder()
                    .bucket(bucketName)
                    .key(objectKey)
                    .build();
            // 下载并写入本地文件
            s3.getObject(request, ResponseTransformer.toFile(new File(localFilePath)));
            System.out.println("对象 " + objectKey + " 下载成功，保存路径：" + localFilePath);
        } catch (S3Exception e) {
            System.err.println("下载失败：" + e.awsErrorDetails().errorMessage());
        } finally {
            s3.close();
        }
    }

    // 4. 列出桶内所有对象（简化版）
    public static void listObjects(String bucketName) {
        S3Client s3 = getS3Client();
        try {
            ListObjectsV2Request request = ListObjectsV2Request.builder()
                    .bucket(bucketName)
                    .build();
            ListObjectsV2Response response = s3.listObjectsV2(request);
            List<S3Object> objects = response.contents();
            System.out.println("桶 " + bucketName + " 中的对象：");
            for (S3Object obj : objects) {
                System.out.println(" - " + obj.key() + "（大小：" + obj.size() + "字节）");
            }
        } catch (S3Exception e) {
            System.err.println("列出对象失败：" + e.awsErrorDetails().errorMessage());
        } finally {
            s3.close();
        }
    }

    // 5. 删除S3中的对象
    public static void deleteObject(String bucketName, String objectKey) {
        S3Client s3 = getS3Client();
        try {
            DeleteObjectRequest request = DeleteObjectRequest.builder()
                    .bucket(bucketName)
                    .key(objectKey)
                    .build();
            s3.deleteObject(request);
            System.out.println("对象 " + objectKey + " 删除成功");
        } catch (S3Exception e) {
            System.err.println("删除失败：" + e.awsErrorDetails().errorMessage());
        } finally {
            s3.close();
        }
    }

    // 测试示例
    public static void main(String[] args) {
        String bucketName = "your-unique-bucket-name"; // 替换为你的桶名（全局唯一）
        String objectKey = "example/upload/test.txt"; // S3中的对象路径
        String localUploadPath = "local-test.txt"; // 本地待上传文件路径
        String localDownloadPath = "downloaded-test.txt"; // 下载后保存的路径

        // 执行操作（按需要注释/取消注释）
        createBucket(bucketName);
        uploadObject(bucketName, objectKey, localUploadPath);
        listObjects(bucketName);
        downloadObject(bucketName, objectKey, localDownloadPath);
        // deleteObject(bucketName, objectKey); // 谨慎使用删除操作
    }
}
